package com.example.howard.mytcpclient;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {
    //UI视图的定义
    private ListView lv_content;
    private EditText edit_send;
    private Button btn_send;
    private FastJsonTools fastJsonTools;
    //聊天内容的显示窗口定义
    private ShowLogView showLogView = new ShowLogView(this);
    private ShowLogViewAdapter showLogViewAdapter;
    private List<String> contentList = new ArrayList<>();
    private com.example.howard.mytcpclient.ConnectService connectService;
    private final String TAG = "MainActivity";
    private MyApplication myApplication;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myApplication=(MyApplication)getApplication();
        FastJsonTools fastJsonTools = new FastJsonTools();
        //设置共享键值信息
//        mapp=(MyApplication) getApplication();
//
//        changkeyHandler = new MyHandler(this);
//        mapp.setChangkeyHandler(changkeyHandler);
    //初始化UI内容及按键功能
        initView();
    }

    private void initView() {
        lv_content = (ListView) findViewById(R.id.list);
        edit_send = (EditText) this.findViewById(R.id.edit_send);
        btn_send = (Button) this.findViewById(R.id.btn_send);
        showLogViewAdapter = new ShowLogViewAdapter(this, contentList);
        lv_content.setAdapter(showLogViewAdapter);
        //发送消息按键功能定义
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg = edit_send.getText().toString().trim();
                if (!connectService.sendMsg(msg)) {
                    Toast.makeText(MainActivity.this, "thread not connect", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        initService();
    }

    @Override
    protected void onPause() {
        unbindService(connection);
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }


    @Override
    protected void onDestroy() {
        stopService(new Intent(this, ConnectService.class));
        super.onDestroy();
    }

    //启动和绑定服务
    private void initService() {

        startService(new Intent(this, ConnectService.class));
        bindService(new Intent(this, ConnectService.class), connection, BIND_AUTO_CREATE);

    }

    //绑定服务参数设置
    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {

            connectService = ((ConnectService.ConnectBinder) binder).getService();

            connectService.insertReceiverListener(new MyHandler(MainActivity.this));
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    //对列表进行转变
    private void modifyList(List<String> result, List<String> branch) {
        result.clear();
        for (int i = 0; i < branch.size(); i++) {
            result.add(branch.get(i));
        }
    }

    //显示聊天内容键值的定义
    private final static int SEND_MSG_SHOW = 123;
//    private final static int CONNECT=1234;

    //自定义MyHandler
    public class MyHandler extends Handler {
        //弱引用
        WeakReference<MainActivity> mActivity;

        MyHandler(MainActivity activity) {
            mActivity = new WeakReference<MainActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg1) {
            MainActivity theActivity = mActivity.get();
            switch (msg1.what) {
                //显示接受到的聊天信息
                case SEND_MSG_SHOW:
                    Log.d(TAG,"receive msg");
                    AllBean allBean = JSONObject.parseObject((String) msg1.obj,AllBean.class);
//                    String jsonString = FastJsonTools.createJsonString((String)msg1.obj);
//                    AllBean allBean =FastJsonTools.createJsonBean(jsonString,AllBean.class);
//                    theActivity.showLogView.addContent((String) msg1.obj);
                    theActivity.showLogView.addContent(allBean.toString());
                    theActivity.modifyList(contentList, showLogView.getCurrentContentList());
                    theActivity.showLogViewAdapter.notifyDataSetChanged();
                    break;
//                //接受连接键的改变值，并存于keyname中
//                case CONNECT:
//                    theActivity.keyname = (String) msg1.obj;
//                    break;
            }
            super.handleMessage(msg1);
        }
    }

    //设置按键的两个按钮键值
    protected static final int MENU_ABOUT = Menu.FIRST;
    protected static final int MENU_QUIT = Menu.FIRST + 2;
    protected static final int MENU_CLIENT = Menu.FIRST + 1;
//    private static final int KEY=2234;
    //连接按键的功能设置，跳转到连接活动
    private void openOptionDiglog() {
        Intent intent = new Intent();
        intent.setClass(MainActivity.this, ConnectActivity.class);
        startActivity(intent);
    }
    //显示服务器已连接的客户端
    private void openClientList(){
        myApplication.getService(connectService);
        Intent intent = new Intent();
        intent.setClass(MainActivity.this, ClientList.class);

        startActivity(intent);
    }
    //设置两个设置按键的名称
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        menu.add(0, MENU_ABOUT, 0, "连接");
        menu.add(0,MENU_CLIENT,0,"客户端");
        menu.add(0, MENU_QUIT, 0, "退出");
        return super.onCreateOptionsMenu(menu);
    }

    //相应设置按键
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case MENU_ABOUT:
                openOptionDiglog();
                break;
            case MENU_CLIENT:
                openClientList();
                break;
            case MENU_QUIT:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
